package com.wxh.utils;


import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @ClassName: WeatherUtils
 * @Description: 天气预报工具类
 * @Author wxh
 * @Date: 2020/9/8 17:22
 * @Version V1.0.0
 * @Since 1.8
 */
public final class WeatherUtils {
    private final static Logger log = LoggerFactory.getLogger(WeatherUtils.class);

    private WeatherUtils(){

    }

    public static void main(String[] args) throws Exception {
        System.out.println(getWeatherByHttp("深圳"));
        System.out.println(getWeatherByHttp("上海"));
    }



    /**
     * 获取天气预报度数
     * @param city 地市名称
     * @return float float类型
     */
    public static float getWeatherByHttp(String city) {
        String url = "http://wthrcdn.etouch.cn/weather_mini?";
        ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("city", city));
        String param = URLEncodedUtils.format(params, "utf-8");
        HttpGet httpGet = new HttpGet(url + param);
        HttpClient httpClient = new DefaultHttpClient();

        HttpResponse httpResponse = null;
        float low = 0;
        try {
            httpResponse = httpClient.execute(httpGet);
            // 获取到解压缩之后的字符串
            String result = getJsonStringFromGZIP(httpResponse);
            System.out.println(result);
            // 输出
            JSONObject jsonObject = JSONObject.fromObject(result);
            JSONObject jsonData = jsonObject.getJSONObject("data");
            String forecast = jsonData.getString("forecast");
            JSONArray array = JSONArray.fromObject(forecast);
            String json = array.getString(0);
            JSONObject Object = JSONObject.fromObject(json);

            String Slow = Object.getString("low");
            // 最低温
            low = NumberUtils.toFloat(Slow.substring(2, Slow.length() - 1).trim(), 0);
            // String Shigh = Object.getString("high");// float
            // 最高温
            // high=NumberUtils.toFloat(Shigh.substring(2,Shigh.length()-1).trim(), 0);
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return low;
    }

    /**
     * GZIP转换为字符串
     * @param response http响应对象
     * @return String 字符串
     */
    private static String getJsonStringFromGZIP(HttpResponse response) {
        String jsonString = null;
        try {
            InputStream is = response.getEntity().getContent();
            BufferedInputStream bis = new BufferedInputStream(is);
            bis.mark(2);
            // 取前两个字节
            byte[] header = new byte[2];
            int result = bis.read(header);
            // reset输入流到开始位置
            bis.reset();
            // 判断是否是GZIP格式
            int headerData = getShort(header);
            if (result != -1 && headerData == 0x1f8b) {
                is = new GZIPInputStream(bis);
            } else {
                is = bis;
            }
            InputStreamReader reader = new InputStreamReader(is, "utf-8");
            char[] data = new char[100];
            int readSize;
            StringBuffer sb = new StringBuffer();
            while ((readSize = reader.read(data)) > 0) {
                sb.append(data, 0, readSize);
            }
            jsonString = sb.toString();
            bis.close();
            reader.close();
        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return jsonString;
    }

    /**
     * 字节数组转换为int
     * @param data 数组对象
     * @return int int类型
     */
    private static int getShort(byte[] data) {
        return (int) ((data[0] << 8) | data[1] & 0xFF);
    }

}

